# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper




class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "大家超惠保重大疾病保险"

    def genProductInfo(self):
        plan = {

            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 11)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000", "400000", "500000"],
                # 交费间隔
                "interval": ["10", "20", "30"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["终身"],
                # 投保对象
                "payObject": ["子女"],
                # 身故保障责任
                "seriousDeath": ["0"],
                # 中病赔付
                "midDisease": ["0", "1"],
                # 轻疾赔付
                "slightDisease": ["0", "1"],
                # 特疾赔付
                "specialDisease": ["0", "1"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(0, 11)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000"],
                # 交费间隔
                "interval": ["10", "20", "30"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["终身"],
                # 投保对象
                "payObject": ["子女"],
                # 身故保障责任
                "seriousDeath": ["1"],
                # 中病赔付
                "midDisease": ["0", "1"],
                # 轻疾赔付
                "slightDisease": ["0", "1"],
                # 特疾赔付
                "specialDisease": ["0", "1"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(11, 19)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000", "400000", "500000"],
                # 交费间隔
                "interval": ["10", "20", "30"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["终身"],
                # 投保对象
                "payObject": ["子女"],
                # 身故保障责任
                "seriousDeath": ["0", "1"],
                # 中病赔付
                "midDisease": ["0", "1"],
                # 轻疾赔付
                "slightDisease": ["0", "1"],
                # 特疾赔付
                "specialDisease": ["0", "1"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(19, 36)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000", "400000", "500000"],
                # 交费间隔
                "interval": ["10", "20", "30"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["终身"],
                # 投保对象
                "payObject": ["本人/子女/配偶/父母"],
                # 身故保障责任
                "seriousDeath": ["0", "1"],
                # 中病赔付
                "midDisease": ["0", "1"],
                # 轻疾赔付
                "slightDisease": ["0", "1"],
                # 特疾赔付
                "specialDisease": ["0", "1"]
            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(36, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", "200000", "300000", "400000", "500000"],
                # 交费间隔
                "interval": ["10", "20"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["终身"],
                # 投保对象
                "payObject": ["本人/子女/配偶/父母"],
                # 身故保障责任
                "seriousDeath": ["0", "1"],
                # 中病赔付
                "midDisease": ["0", "1"],
                # 轻疾赔付
                "slightDisease": ["0", "1"],
                # 特疾赔付
                "specialDisease": ["0", "1"]

            }

        }

        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["interval"],
                             plan[k]["payType"], plan[k]["expire"], plan[k]["payObject"], plan[k]["seriousDeath"],
                             plan[k]["midDisease"], plan[k]["slightDisease"], plan[k]["specialDisease"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10]
                ))

    # 执行爬虫
    def requestJson(self, dt=None, null="null"):

        if (dt["specialDisease"]=="0" and dt["specialDisease"]=="0" and ["specialDisease"]=="0" and ["specialDisease"]=="0"):
            print("无任何附加保险")
            data = {"planCode": "L16056", "packageCode": null, "insureds": [
                {"mainInsuredFlag": "Y", "relationToHolder": "1",
                 "birthday": "{0}-05-05".format(str(2020 - int(dt["year"]))),
                 "gender": "1" if dt["gender"] == "F" else "0"}],
                    "products": [
                        {"productCode": "L16056", "copies": "1", "chargePeriodType": "1",
                         "chargePeriod": dt["interval"],
                         "chargeFrequency": "1" if dt["payType"] == "年交" else "4", "coveragePeriodType": "5",
                         "coveragePeriod": "0",
                         "sumInsured": dt["money"],
                         "liabilities": [{"copies": "1", "sumInsured": dt["money"], "liabilityCode": "605601"}]}]}

            payload = json.dumps(data)

            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "您的操作成功" in r.text:

                price = Helper.decimalParse(r.json()["body"]["regularPremium"])

                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                self.mysql.updatePrice( data )

            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                self.mysql.updateTask( data )
                print("\n/*产品价格更新失败:%d*/"%dt["id"])


        else:
            # 定义列表容器
            results = [{"copies": "1", "sumInsured": dt["money"], "liabilityCode": "605601"}]

            items = {

                "seriousDeath": dt["seriousDeath"],
                "midDisease": dt["midDisease"],
                "slightDisease": dt["slightDisease"],
                "specialDisease": dt["specialDisease"]
            }

            for k, v in items.items():

                if v == "0":
                    pass

                else:

                    if k == "seriousDeath":
                        print("投保重疾")

                        results.append({"copies": "1", "sumInsured": dt["money"], "liabilityCode": "605602"})

                    elif k == "midDisease":
                        print("投保中疾")

                        results.append(
                            {"copies": "1", "sumInsured": str(int(int(dt["money"]) * 0.5)), "liabilityCode": "605604"})
                        results.append( {"liabilityCode":"605606"} )

                    elif k == "slightDisease":
                        print("投保轻疾")

                        results.append(
                            {"copies": "1", "sumInsured": str(int(int(dt["money"]) * 0.3)), "liabilityCode": "605605"})
                        results.append( {"liabilityCode":"605607"} )

                    else:
                        print("投保特疾")

                        results.append(
                            {"copies": "1", "sumInsured": str(int(int(dt["money"]) * 0.3)), "liabilityCode": "605603"})

            data = {"planCode": "L16056", "packageCode": null, "insureds": [
                {"mainInsuredFlag": "Y", "relationToHolder": "1",
                 "birthday": "{0}-05-05".format(str(2020 - int(dt["year"]))),
                 "gender": "1" if dt["gender"] == "F" else "0"}],
                    "products": [
                        {"productCode": "L16056", "copies": "1", "chargePeriodType": "1", "chargePeriod": dt["interval"],
                         "chargeFrequency": "1" if dt["payType"] == "年交" else "4", "coveragePeriodType": "5",
                         "coveragePeriod": "0",
                         "sumInsured": dt["money"],
                         "liabilities": results}]}


            payload = json.dumps(data)

            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "您的操作成功" in r.text:

                price = Helper.decimalParse(r.json()["body"]["regularPremium"])

                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }
                self.mysql.updatePrice(data)

            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                self.mysql.updateTask(data)
                print("\n/*产品价格更新失败:%d*/" % dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
